package com.pan.hisystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pan.hisystem.pojo.MedicalCard;
import com.pan.hisystem.mapper.MedicalCardMapper;
import com.pan.hisystem.pojo.Patient;
import com.pan.hisystem.pojo.RespBean;
import com.pan.hisystem.service.IMedicalCardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pan.hisystem.service.IPatientService;
import com.pan.hisystem.utils.IdCardValidUtil;
import com.pan.hisystem.utils.IdUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.IdUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qingyang
 * @since 2022-03-11
 */
@Service
public class MedicalCardServiceImpl extends ServiceImpl<MedicalCardMapper, MedicalCard> implements IMedicalCardService {

    @Autowired
    private MedicalCardMapper medicalCardMapper;
    @Autowired
    private IPatientService patientService;


    /**
     * 新办就诊卡
     * @param medicalCard
     * @return
     */
    @Override
    @Transactional
    public RespBean addMCard(MedicalCard medicalCard) {
        boolean flag= IdCardValidUtil.validateIdCard(medicalCard.getIdCard());
        if(!flag){
            return RespBean.error("身份证号码格式有误!");
        }
        if(!IdUtils.isMobile(medicalCard.getTelephone())){
            return RespBean.error("手机号码格式有误");
        }
        String mid= IdUtils.getMId();
        System.out.println("生成就诊卡号:"+mid);
        medicalCard.setId(mid);
        int i=0;
        //判断该就诊卡号是否存在重复,重复则重新生成卡号
        while(medicalCardMapper.selectOne(new QueryWrapper<MedicalCard>().eq("id",medicalCard.getId()))!=null){
            mid= IdUtils.getMId();
            medicalCard.setId(mid);
        }

        //不重复则添加该就诊卡
        i=medicalCardMapper.insert(medicalCard);

        if(i==1){
            //将就诊卡号与患者信息绑定
            Patient patient=new Patient();
            patient.setMid(medicalCard.getId());
            patient.setAge(IdCardValidUtil.getAgeByIdCard(medicalCard.getIdCard()));
            patient.setBirthday(IdCardValidUtil.getBirthByIdCard2(medicalCard.getIdCard()));
            patient.setProvince(IdCardValidUtil.getProvinceByIdCard(medicalCard.getIdCard()));
            if(patientService.save(patient)){
                return RespBean.success("添加成功!");
            }
        }
        return RespBean.error("添加失败!");
    }

}
